<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;

use think\Request;

//门店销售
class Sale extends Base
{
    public function _initialize()
    {
        parent::_initialize();
        $this->model = 'store_order';
        $defaultWhere = $this->getDefaultWhere();
        $this->defaultWhere = $defaultWhere;
        $storeMdl = model('store');
        $store = $storeMdl->field('id,name')->select();
        $this->assign('store',$store);
    }

    public function index(){
        $request = $this->request;
        $param = $request->param();
        // Reset filter
        if ($request->param('reset')) {
            return redirect(fullUrl($request->path()));
        }
        if($request->isAjax()){
            $model = model($this->model);

            // 每页起始条数
            $start = ($param['page'] - 1) * $param['limit'];
            // 每页显示条数
            $length = $param['limit'] + 1;
            // 排序条件
            $order = '';

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                $where = array_merge($this->defaultWhere, $where);
            }
            if($this->defaultOrder){
                $order = $this->defaultOrder;
            }
            $fields = 'a.id, a.order_no, a.pay_time, a.pay_price,a.member_account, a.discount_price, a.pay_type, s.name, f.name as staffName , o.id as order_id';
            $data = $model->alias('a')
                ->where($where)
                ->join('store s','a.store_id = s.id')
                ->join('store_member f','a.cash_register = f.id')
                ->join('order o','a.order_no = o.order_no')
                ->field($fields)
                ->limit($start, $length)
                ->order($order)->select();
            if (!$data){
                return $this->error('未查询到数据');
            }
            $count = $model->where($where)->count();
            foreach($data as $v)
            {
                if (!empty($v['member_account'])){
                    $memberMdl = model('member');
                    $item = $memberMdl->where('account_number',$v['account_number'])->find();
                    $v['member_account'] = $item['member_account'];
                }else{
                    $v['member_account'] = '-';
                }
                $orderSnapshotMdl = model('OrderSnapshot');
                $productMdl = model('product');
                $orderSnapshot = $orderSnapshotMdl->where('order_id',$v['order_id'])->field('count,product_id')->select();
                $member_integral = 0;
                foreach($orderSnapshot as $orderVal)
                {
                    $integral = $productMdl->where('id',$orderVal['product_id'])->field('member_integral')->find();
                    $member_integral += $integral['member_integral'] * $orderVal['count'];
                }
                if ($member_integral != 0){
                    $v['member_integral'] = $member_integral;
                }else{
                    $v['member_integral'] = '-';
                }
                $v['pay_type'] = show_pay_type($v['pay_type']);
                $v['pay_price'] = $v['pay_price'] /100;
                $v['discount_price'] = $v['discount_price'] /100;
                $v['pay_reality'] = $v['pay_price'] + $v['discount_price'];
            }
            $result = [
                'code' => '0',
                'msg' => '请求成功',
                'data' => $data,
                'count' => $count,
            ];

            return json($result);
        }

        return self::show($this->indexView, [
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param()
        ]);
    }

    /**
     * Add
     */
    public function add(Request $request){

        return parent::add($request);
    }

    /**
     * Add Post
     */
    public function addPost(Request $request, $redirect = ''){

        return parent::addPost($request, '');
    }

    /**
     * Edit
     */
    public function edit(Request $request){

        return parent::edit($request);
    }

    /**
     * Detail
     */
    public function detail(){
        $request = $this->request;
        $model = model($this->model);
        $param = $request->param();
        $id = $param['id'];
        $where['a.id'] = $id;
        $fields = 'a.id,order_no,pay_time,pay_price,discount_price,pay_type,s.name';
        $info = $model->alias('a')
            ->where($where)
            ->field($fields)
            ->join('store s','a.store_id = s.id')
            ->find();

        $info['pay_type'] = show_pay_type($info['pay_type']);

        $info['pay_price'] = $info['pay_price'] /100 .'.00';
        $info['discount_price'] = $info['discount_price'] /100 .'.00';
        $info['pay_reality'] = $info['pay_price'] - $info['discount_price'] .'.00';

        $this->assign('info',$info);

        $this->assign('id',$id);

        // Reset filter
        if ($request->param('reset')) {
            return redirect(fullUrl($request->path()));
        }
        if($request->isAjax()){
            $orderMdl = model('order');
            $order = $orderMdl->where('order_no',$info['order_no'])->field('id')->find();
            $orderId = $order['id'];
            $orderSnapshotMdl = model('order_snapshot');
            $data = $orderSnapshotMdl->where('order_id',$orderId)->select();
            if (!$data){
                return $this->error('未查询到详情');
            }
            $result = [
                'code' => '0',
                'msg' => '请求成功',
            ];

            return json($result);
        }

        return self::show('detail', [
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param()
        ]);
    }

    /**
     * Edit Post
     */
    public function editPost(Request $request, $redirect = ''){

        return parent::editPost($request, '');
    }

    private function show($template, $data = []) {

        return $this->view->fetch($template, $data);
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if(isset($param['order_no']) && $param['order_no']){
            $where['order_no'] = ['like', '%'.$param['order_no'].'%'];
        }
        if(isset($param['store_id']) && $param['store_id']){
            $where['store_id'] = $param['store_id'];
        }
        if(isset($param['pay_type']) && $param['pay_type']){
            $where['pay_type'] = $param['pay_type'];
        }
        if(isset($param['time']) && $param['time']){
            $where['time'] = str_replace('+','',$param['time']);
            $where['time'] = preg_replace('# #','',$where['time']);
            $where['time'] = explode ('到',$where['time']);
            $where['pay_time'] = ['between',[$where['time'][0],$where['time'][1]]];
        }

        return $where;
    }
}